var express = require('express');
var router = express.Router();
let md5 = require('md5');
let config = require('../config/config');
let {isPhone, isEmail, randomString} = require('../utils/utils')
//let connection = require('../utils/mysql');
let {User, Session} = require('../database/sequelize')

router.post('/login', async function (req, res, next) {

  let account = req.body.account;
  let password = req.body.password;

  //过滤空字符
  if (!account || !password) {
    res.send({"success": false, "msg": "账号或者密码为空"});
    return
  }

  //加密
  password = md5(config.salt + password);

  let data = null;

  //判断是电话
  if (isPhone(account)) {

    await User.findOne({where: {phone: account, password: password}}).then(project => {
      if (project) {
        data = project.dataValues;
      }

    })
    //判断是邮箱
  } else if (isEmail(account)) {

    await User.findOne({where: {email: account, password: password}}).then(project => {
      if (project) {
        data = project.dataValues;
      }
    })

  } else {
    res.send({"success": false, "msg": "账号应为邮箱或者电话"});
    return
  }

  let session_id = null;
  //session处理
  if (data) {
    await Session.create({
      id: randomString(),
      userinfo: JSON.stringify(data),
      expired: (new Date().getTime()) / 1000 + (30 * 60)
    }).then(session => {
      session_id = session.dataValues.id
    });
  }

  if (data && session_id) {
    delete data.password;
    res.send({"success": true, "msg": "success", session_id: session_id});
  } else {
    res.send({"success": false, "msg": "失败，账号密码不正确"});
  }


});

module.exports = router;
